package com.mhkj.base.templete.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.mhkj.base.busiType.service.BusinessTypeService;
import com.mhkj.base.fruitType.entity.FruitType;
import com.mhkj.base.fruitType.service.FruitTypeService;
import com.mhkj.base.templete.entity.PlanTemplete;
import com.mhkj.base.templete.entity.PlanTempleteData;
import com.mhkj.base.templete.repostitory.PlanTempleteRepository;
import com.mhkj.base.templete.service.PlanTempleteDataService;
import com.mhkj.base.templete.service.PlanTempleteService;
import com.mhkj.common.enums.ApplyState;
import com.mhkj.common.enums.PlanTempleteType;
import com.mics.core.common.componet.Pagination;
import com.mics.core.common.exception.ErrorCode;
//import com.mics.core.common.exception.OperateException;
import com.mics.core.common.exception.ParamException;
import com.mics.core.common.util.file.ExcelUtils;
import com.mics.core.system.base.service.FileService;
import com.mics.core.system.base.service.impl.BaseServiceImpl;
import com.mics.core.system.organizational.bean.Employee;
import com.mics.core.system.organizational.service.OrgService;
import com.mics.core.system.rbac.entity.Dictionary;
import com.mics.core.system.rbac.service.DictionaryService;

/**
 * 计划模板服务实现
 * @author mics
 * @date 2018年7月2日
 * @version 1.0	
 */
@Service
public class PlanTempleteServiceImpl extends BaseServiceImpl<PlanTemplete> implements PlanTempleteService{
	@Resource
	private PlanTempleteRepository planTempleteRepository;
	@Resource
	private BusinessTypeService businessTypeService;
	@Resource
	private FileService fileService;
	@Resource
	private OrgService orgService;
	@Resource
	private PlanTempleteDataService planTempleteDataService;
	@Resource
	private DictionaryService dictionaryService;
	@Resource
	private FruitTypeService fruitTypeService;
	
	@Resource
	public void setPlanTempleteRepository(
			PlanTempleteRepository planTempleteRepository) {
		super.setBaseRepository(planTempleteRepository);
	}

	@Override
	public Pagination<PlanTemplete> listByPage(PlanTemplete planTemplete,
			int pageIndex, int size) {
		Specification<PlanTemplete> spec = new Specification<PlanTemplete> () {  
			/**
			 * 序列号
			 */
			private static final long serialVersionUID = -786003485941679959L;
			@Override
			public Predicate toPredicate(Root<PlanTemplete> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
	          Join<Object, Object> type = root.join("type",JoinType.INNER);
              List<Predicate> lstPredicates = new ArrayList<Predicate>();
              if(!StringUtils.isEmpty(planTemplete.getName())){
                  Predicate p1=criteriaBuilder.like(root.get("name").as(String.class), "%"+planTemplete.getName()+"%");
                  lstPredicates.add(p1);
              }
              if(planTemplete.getType() != null ){
                  Predicate p2=criteriaBuilder.equal(type.get("id").as(Long.class), planTemplete.getType().getId());
                  lstPredicates.add(p2);
              }
              Predicate[] arrayPredicates = new Predicate[lstPredicates.size() ];
              return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
	        }
		};
		Page<PlanTemplete> pageT =  planTempleteRepository.findAll(spec, PageRequest.of(pageIndex, size, Sort.Direction.ASC,"id"));
		Pagination<PlanTemplete> pagination = new Pagination<PlanTemplete>();
		pagination.setTotal(planTempleteRepository.count(spec));
		List<PlanTemplete> planTempletes = pageT.getContent();
		for(PlanTemplete planTemplete2 : planTempletes){
			Employee employee = orgService.employeeInfo(planTemplete2.getCreateBy());
			planTemplete2.setCreateUserName(employee.getName());
		}
		pagination.setData(planTempletes);
		return pagination;
	}

	
	@Override
	@Transactional
	public String save(PlanTemplete planTemplete) {
		Dictionary type = dictionaryService.getById(planTemplete.getType().getId());
		planTemplete.setType(type);
		if(planTemplete.getProfessionalType().getId() == null){
			planTemplete.setProfessionalType(null);
		}
		String message = super.save(planTemplete);
		return message;
	}

	@Override
	@Transactional
	public String edit(PlanTemplete planTemplete) {
		PlanTemplete planTempleted = getById(planTemplete.getId());
		planTemplete.setState(planTempleted.getState());
		return super.edit(planTemplete);
	}

	@Override
	@Transactional
	public String del(PlanTemplete planTemplete) {
		PlanTemplete planTempleted = getById(planTemplete.getId());
		if(planTempleted.getState()==ApplyState.submit.getState() || planTemplete.getState()==ApplyState.checkSuccess.getState()){
			return "已经提交或者审核通过得模板不能删除";
		}
		if(planTempleted.getFruitTypes() != null && planTempleted.getFruitTypes().size() > 0){
			for(FruitType fruitType:planTempleted.getFruitTypes()){
				fruitTypeService.del(fruitType);
			}
		}
		
		for(PlanTempleteData planTempleteData:planTempleted.getPlanTempleteDatas()){
			planTempleteDataService.del(planTempleteData);
		}
		String message = "error";
		try{
			message = super.del(planTemplete);
		}catch(Exception e){
			//throw new OperateException(ErrorCode.DELETE, "删除模板失败");
		}
		return message;
	}

	@Override
	@Transactional
	public String save(PlanTemplete planTemplete, MultipartFile file) {
		String[][] result = ExcelUtils.getData(file, 0);
		if(result.length == 0){
			throw new ParamException(ErrorCode.EXCEL_READ_ERROR, "模板数据为空");
		}
		//保存模板
		String message = save(planTemplete);
		if("ok".equals(message)){
			//保存模板数据
			if(planTemplete.getType().getCode().equals(PlanTempleteType.KEY.getCode())){ //关键
				String templeteDataName = result[0][0];
				if(!templeteDataName.contains("关键")){
					throw new ParamException(ErrorCode.EXCEL_READ_ERROR, "请选择关键模板");
				}
			}else if(planTemplete.getType().getCode().equals(PlanTempleteType.MAIN.getCode())){//主项
				String templeteDataName = result[0][0];
				if(!templeteDataName.contains("主项")){
					throw new ParamException(ErrorCode.EXCEL_READ_ERROR, "请选择主项模板");
				}
			}else if(planTemplete.getType().getCode().equals(PlanTempleteType.PROFESSIONAL.getCode())){//专项
				String templeteDataName = result[0][0];
				if(!templeteDataName.contains("专项")){
					throw new ParamException(ErrorCode.EXCEL_READ_ERROR, "请选择专项模板");
				}
			}else if(planTemplete.getType().getCode().equals(PlanTempleteType.FUNCTION.getCode())){//职能
				String templeteDataName = result[0][0];
				if(!templeteDataName.contains("职能")){
					throw new ParamException(ErrorCode.EXCEL_READ_ERROR, "请选择职能模板");
				}
			}
			PlanTemplete planTemplete2 = getById(planTemplete.getId());
			planTempleteDataService.handleData(planTemplete2,result);
		}
		return "ok";
	}

	/**
	 * 根据模板类型取模板
	 */
	@Override
	public List<PlanTemplete> getByTempleteType(long templeteTypeId) {
		List<PlanTemplete> planTempletes = planTempleteRepository.getByTempleteType(templeteTypeId);
		return planTempletes;
	}

	@Override
	public List<PlanTemplete> getByPerfessionTypeId(Long perfessionTypeId) {
		List<PlanTemplete> planTempletes = planTempleteRepository.getByPerfessionType(perfessionTypeId);
		return planTempletes;
	}


	
}
